{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./data/train-images-idx3-ubyte.gz\n",
      "Extracting ./data/train-labels-idx1-ubyte.gz\n",
      "Extracting ./data/t10k-images-idx3-ubyte.gz\n",
      "Extracting ./data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = './data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "# First convolutional layer - maps one grayscale image to 32 feature maps.\n",
    "# 卷积层1：5x5，步长为1\n",
    "with tf.name_scope('conv1'):\n",
    "  h_conv1 = tf.contrib.slim.conv2d(x_image, 32, [5,5],\n",
    "                             stride = 1,\n",
    "                             padding='SAME',\n",
    "                             activation_fn=tf.nn.relu)\n",
    "\n",
    "\n",
    "# Pooling layer - downsamples by 2X.\n",
    "# 池化层1：2x2，步长为2\n",
    "with tf.name_scope('pool1'):\n",
    "  h_pool1 = tf.contrib.slim.max_pool2d(h_conv1, [2,2], stride=2, \n",
    "                         padding='SAME')\n",
    "\n",
    "# Second convolutional layer -- maps 32 feature maps to 64.\n",
    "# 卷积层2：5x5，步长为1\n",
    "with tf.name_scope('conv2'):\n",
    "  h_conv2 = tf.contrib.slim.conv2d(h_pool1, 64, [5,5],\n",
    "                             stride = 1,\n",
    "                             padding='SAME',\n",
    "                             activation_fn=tf.nn.relu)\n",
    "\n",
    "# Second pooling layer.\n",
    "# 池化层2：2x2，步长为2\n",
    "with tf.name_scope('pool2'):\n",
    "  h_pool2 = tf.contrib.slim.max_pool2d(h_conv2, [2,2],\n",
    "                        stride=[2, 2], padding='SAME')\n",
    "\n",
    "\n",
    "# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image\n",
    "# is down to 7x7x64 feature maps -- maps this to 1024 features.\n",
    "# 全连接层，该层不使用激活函数，等到dropout后再激活\n",
    "with tf.name_scope('fc1'):\n",
    "  h_pool2_flat = tf.contrib.slim.avg_pool2d(h_pool2, h_pool2.shape[1:3],\n",
    "                        stride=[1, 1], padding='VALID')\n",
    "  h_fc1 = tf.contrib.slim.conv2d(h_pool2_flat, 1024, [1,1], activation_fn=None)\n",
    "\n",
    "# Dropout - controls the complexity of the model, prevents co-adaptation of\n",
    "# features.\n",
    "with tf.name_scope('dropout'):\n",
    "  keep_prob = tf.placeholder(tf.float32)\n",
    "  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# 先dropout，再进行激活\n",
    "h_fc1_drop_act = tf.nn.relu(h_fc1_drop)\n",
    "\n",
    "# Map the 1024 features to 10 classes, one for each digit\n",
    "# 输出层\n",
    "with tf.name_scope('fc2'):\n",
    "  y = tf.squeeze(tf.contrib.slim.conv2d(h_fc1_drop_act, 10, [1,1], activation_fn=None))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "\n",
    "# l2正则，防止过拟合\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.165418, l2_loss: 103.481873, total loss: 1.172661\n",
      "0.47\n",
      "step 200, entropy loss: 0.873265, l2_loss: 145.390366, total loss: 0.883443\n",
      "0.72\n",
      "step 300, entropy loss: 0.443664, l2_loss: 175.532867, total loss: 0.455951\n",
      "0.92\n",
      "step 400, entropy loss: 0.369488, l2_loss: 197.222824, total loss: 0.383293\n",
      "0.89\n",
      "step 500, entropy loss: 0.421238, l2_loss: 212.994080, total loss: 0.436147\n",
      "0.89\n",
      "step 600, entropy loss: 0.290105, l2_loss: 225.777588, total loss: 0.305910\n",
      "0.92\n",
      "step 700, entropy loss: 0.287962, l2_loss: 236.385208, total loss: 0.304509\n",
      "0.91\n",
      "step 800, entropy loss: 0.215888, l2_loss: 246.578934, total loss: 0.233148\n",
      "0.92\n",
      "step 900, entropy loss: 0.224495, l2_loss: 255.797440, total loss: 0.242401\n",
      "0.95\n",
      "step 1000, entropy loss: 0.179307, l2_loss: 264.085510, total loss: 0.197793\n",
      "0.95\n",
      "0.9492\n",
      "step 1100, entropy loss: 0.175803, l2_loss: 272.501160, total loss: 0.194878\n",
      "0.95\n",
      "step 1200, entropy loss: 0.209408, l2_loss: 282.191681, total loss: 0.229161\n",
      "0.93\n",
      "step 1300, entropy loss: 0.167752, l2_loss: 287.969666, total loss: 0.187910\n",
      "0.97\n",
      "step 1400, entropy loss: 0.265480, l2_loss: 295.049683, total loss: 0.286133\n",
      "0.91\n",
      "step 1500, entropy loss: 0.213958, l2_loss: 301.788300, total loss: 0.235083\n",
      "0.94\n",
      "step 1600, entropy loss: 0.158260, l2_loss: 308.992340, total loss: 0.179890\n",
      "0.96\n",
      "step 1700, entropy loss: 0.178741, l2_loss: 315.612732, total loss: 0.200834\n",
      "0.94\n",
      "step 1800, entropy loss: 0.120037, l2_loss: 320.809418, total loss: 0.142493\n",
      "0.99\n",
      "step 1900, entropy loss: 0.192276, l2_loss: 327.392517, total loss: 0.215194\n",
      "0.96\n",
      "step 2000, entropy loss: 0.113582, l2_loss: 333.161285, total loss: 0.136903\n",
      "0.98\n",
      "0.9639\n",
      "step 2100, entropy loss: 0.103021, l2_loss: 337.377380, total loss: 0.126638\n",
      "0.97\n",
      "step 2200, entropy loss: 0.156781, l2_loss: 343.224396, total loss: 0.180807\n",
      "0.97\n",
      "step 2300, entropy loss: 0.151473, l2_loss: 349.325531, total loss: 0.175926\n",
      "0.96\n",
      "step 2400, entropy loss: 0.133734, l2_loss: 355.446777, total loss: 0.158615\n",
      "0.96\n",
      "step 2500, entropy loss: 0.085548, l2_loss: 359.830414, total loss: 0.110736\n",
      "0.97\n",
      "step 2600, entropy loss: 0.064152, l2_loss: 362.962585, total loss: 0.089560\n",
      "0.99\n",
      "step 2700, entropy loss: 0.110797, l2_loss: 367.321350, total loss: 0.136510\n",
      "0.97\n",
      "step 2800, entropy loss: 0.113740, l2_loss: 371.311493, total loss: 0.139732\n",
      "0.99\n",
      "step 2900, entropy loss: 0.096390, l2_loss: 376.357758, total loss: 0.122735\n",
      "0.97\n",
      "step 3000, entropy loss: 0.130028, l2_loss: 380.239349, total loss: 0.156645\n",
      "0.96\n",
      "0.9724\n",
      "step 3100, entropy loss: 0.053740, l2_loss: 384.249481, total loss: 0.080638\n",
      "1.0\n",
      "step 3200, entropy loss: 0.133919, l2_loss: 387.736053, total loss: 0.161060\n",
      "0.96\n",
      "step 3300, entropy loss: 0.088695, l2_loss: 391.357910, total loss: 0.116090\n",
      "0.96\n",
      "step 3400, entropy loss: 0.146935, l2_loss: 393.364136, total loss: 0.174471\n",
      "0.95\n",
      "step 3500, entropy loss: 0.160975, l2_loss: 398.373260, total loss: 0.188861\n",
      "0.97\n",
      "step 3600, entropy loss: 0.040286, l2_loss: 402.149384, total loss: 0.068436\n",
      "1.0\n",
      "step 3700, entropy loss: 0.242701, l2_loss: 406.719727, total loss: 0.271171\n",
      "0.97\n",
      "step 3800, entropy loss: 0.024857, l2_loss: 408.815918, total loss: 0.053474\n",
      "1.0\n",
      "step 3900, entropy loss: 0.115494, l2_loss: 411.337738, total loss: 0.144288\n",
      "0.97\n",
      "step 4000, entropy loss: 0.059985, l2_loss: 414.779236, total loss: 0.089020\n",
      "0.98\n",
      "0.9804\n",
      "step 4100, entropy loss: 0.071155, l2_loss: 416.879974, total loss: 0.100337\n",
      "0.96\n",
      "step 4200, entropy loss: 0.034254, l2_loss: 418.716431, total loss: 0.063564\n",
      "0.99\n",
      "step 4300, entropy loss: 0.085621, l2_loss: 421.615753, total loss: 0.115135\n",
      "0.97\n",
      "step 4400, entropy loss: 0.077979, l2_loss: 425.352905, total loss: 0.107754\n",
      "0.96\n",
      "step 4500, entropy loss: 0.095270, l2_loss: 427.017181, total loss: 0.125161\n",
      "0.98\n",
      "step 4600, entropy loss: 0.083339, l2_loss: 430.132111, total loss: 0.113448\n",
      "0.98\n",
      "step 4700, entropy loss: 0.068176, l2_loss: 433.017975, total loss: 0.098488\n",
      "0.98\n",
      "step 4800, entropy loss: 0.041869, l2_loss: 436.328064, total loss: 0.072412\n",
      "1.0\n",
      "step 4900, entropy loss: 0.077206, l2_loss: 437.714325, total loss: 0.107846\n",
      "0.99\n",
      "step 5000, entropy loss: 0.076256, l2_loss: 439.495575, total loss: 0.107020\n",
      "0.98\n",
      "0.982\n",
      "step 5100, entropy loss: 0.043609, l2_loss: 441.671906, total loss: 0.074526\n",
      "0.99\n",
      "step 5200, entropy loss: 0.015665, l2_loss: 442.757111, total loss: 0.046658\n",
      "1.0\n",
      "step 5300, entropy loss: 0.036607, l2_loss: 445.400146, total loss: 0.067785\n",
      "1.0\n",
      "step 5400, entropy loss: 0.070333, l2_loss: 447.182465, total loss: 0.101636\n",
      "0.98\n",
      "step 5500, entropy loss: 0.052434, l2_loss: 449.600616, total loss: 0.083906\n",
      "0.99\n",
      "step 5600, entropy loss: 0.107332, l2_loss: 450.668915, total loss: 0.138879\n",
      "0.98\n",
      "step 5700, entropy loss: 0.052745, l2_loss: 452.486725, total loss: 0.084420\n",
      "0.98\n",
      "step 5800, entropy loss: 0.029487, l2_loss: 454.477661, total loss: 0.061300\n",
      "0.98\n",
      "step 5900, entropy loss: 0.085869, l2_loss: 456.547485, total loss: 0.117827\n",
      "0.98\n",
      "step 6000, entropy loss: 0.019406, l2_loss: 459.023773, total loss: 0.051538\n",
      "0.99\n",
      "0.9823\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(6000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  # 学习率设置为le-3，加快收敛速度，但是3000次迭代，总是到不了0.98，增加迭代次数，分数提升\n",
    "  lr = 1e-3\n",
    "  _, loss, l2_loss_value, total_loss_value = sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr, keep_prob:0.5})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    # Test trained model\n",
    "    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    print(sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys, keep_prob:0.5}))\n",
    "  if (step+1) % 1000 == 0:\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels, keep_prob:1.0}))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
